package chapter1.dao.collection;

import chapter1.dao.IBaseDao;
import chapter1.domain.entity.BaseEntity;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据访问层基类-基于容器存储数据
 *
 * @author 郑植航
 * @since 2025/6/16 00:11
 */
abstract class BaseDao<Entity extends BaseEntity> implements IBaseDao<Entity> {

    Map<Integer,Entity> data= new HashMap<>();

    private int idCounter = 1;

    @Override
    public boolean existById(int id) {
        return data.containsKey(id);
    }

    @Override
    public Entity findById(int id) {
        return data.get(id);
    }

    @Override
    public Collection<Entity> list() {
        return data.values();
    }

    @Override
    public Entity save(Entity entity) {
        Integer id = entity.getId();
        if(id==null){
            id=idCounter++;
            entity.setId(id);
        }
        data.put(id,entity);
        return entity;
    }

    @Override
    public Entity delete(int id) {
        return data.remove(id);
    }
}
